<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Frontend_Forum extends Controller_Frontend {
	
	public function action_sections()
	{
		$view = new View('frontend/forum.sections.index');
		
		$sections = ORM::factory('Forum_Section')->order_by('sort', 'asc')->find_all();
		$view->sections = $sections;
		
		$this->template->content = $view;
	}
	
	public function action_section()
	{
		$view = new View('frontend/forum.section.index');
		
		$id = Request::current()->param('id');
		
		$section = ORM::factory('Forum_Section')->where('id', '=', $id)->find();
		$view->section = $section;
		
		if ( ! isset($section->id))
			throw new HTTP_Exception_404;
		
		$this->template->content = $view;
	}
	
	public function action_cat()
	{
		$view = new View('frontend/forum.cat.index');
		
		$id = Request::current()->param('id');
		$page = Request::current()->param('page');
		
		Cookie::set('frontend_forum_cat_'.$id.'_page', $page > 1 ? $page : NULL);
		
		$cat = ORM::factory('Forum_Cat')->where('id', '=', $id)->find();
		$view->cat = $cat;
		
		if ( ! isset($cat->id))
			throw new HTTP_Exception_404;
		
		$section = ORM::factory('Forum_Section')->where('id', '=', $cat->section_id)->find();
		$view->section = $section;
		
		if ( ! isset($section->id))
			throw new HTTP_Exception_404;
		
		$pagination = Pagination::factory(array(
			'total_items' => ORM::factory('Forum_Topic')->where('cat_id', '=', $cat->id)->count_all(),
		))->route_params(array(
			'controller' => Request::current()->controller(),
			'action' => Request::current()->action(),
			'id' => Request::current()->param('id'),
		));
		$view->pagination = $pagination;
		
		$topics = ORM::factory('Forum_Topic')->where('cat_id', '=', $cat->id)
			->order_by('date', 'ASC')->limit($pagination->items_per_page)->offset($pagination->offset)
			->find_all();
		$view->topics = $topics;
		
		$this->template->content = $view;
	}
	
	public function action_topic()
	{
		$view = new View('frontend/forum.topic.index');
		
		$id = Request::current()->param('id');
		$page = Request::current()->param('page');
		
		Cookie::set('frontend_forum_topic_'.$id.'_page', $page > 1 ? $page : NULL);
		
		$topic = ORM::factory('Forum_Topic')->where('id', '=', $id)->find();
		$view->topic = $topic;
		
		if ( ! isset($topic->id))
			throw new HTTP_Exception_404;
		
		$cat = ORM::factory('Forum_Cat')->where('id', '=', $topic->cat_id)->find();
		$view->cat = $cat;
		
		if ( ! isset($cat->id))
			throw new HTTP_Exception_404;
		
		$section = ORM::factory('Forum_Section')->where('id', '=', $cat->section_id)->find();
		$view->section = $section;
		
		if ( ! isset($section->id))
			throw new HTTP_Exception_404;
		
		$pagination = Pagination::factory(array(
			'total_items' => ORM::factory('Forum_Message')->where('topic_id', '=', $topic->id)->count_all(),
		))->route_params(array(
			'controller' => Request::current()->controller(),
			'action' => Request::current()->action(),
			'id' => Request::current()->param('id'),
		));
		$view->pagination = $pagination;
		
		$messages = ORM::factory('Forum_Message')
			->where('topic_id', '=', $topic->id)->order_by('date', 'ASC')
			->limit($pagination->items_per_page)->offset($pagination->offset)
			->find_all();
		$view->messages = $messages;
		
		$subscribed = ORM::factory('Forum_Subscribe')
			->where('topic_id', '=', $topic->id)->where('user_id', '=', $topic->user_id)
			->find();
		$view->subscribed = $subscribed;
		
		$tviews = ORM::factory('Forum_Topic_View');
		$tviews->user_id = Model_Reg::get('user')->id;
		$tviews->topic_id = $topic->id;
		$tviews->date = time();
		$tviews->save();
		
		if (Model_Reg::get('user')->id > 0)
		{
			$unreaded = ORM::factory('Forum_Topic_Unreaded')
				->where('topic_id', '=', $topic->id)->where('user_id', '=', Model_Reg::get('user')->id)
				->find_all();
			
			foreach ($unreaded as $u) $u->delete();
		}
		
		$this->template->content = $view;
	}
	
	public function action_goto()
	{
		$id = Request::current()->param('id');
		
		$message = ORM::factory('Forum_Message')->where('id', '=', $id)->find();
		
		if ( ! isset($message->id))
			throw new HTTP_Exception_404;
		
		$pagination = Pagination::factory();
		$position = ORM::factory('Forum_Message')->where('topic_id', '=', $message->topic_id)->where('id', '<=', $message->id)->count_all();
		$page = ceil($position / $pagination->items_per_page);
		
		Request::current()->redirect(URL::site(Route::get('frontend_forum')->uri(array(
			'action' => 'topic',
			'id' => $message->topic->id,
			'page' => ($page > 1) ? $page : NULL,
		)), TRUE).'#message'.$message->id);
	}
	
	public function action_preview()
	{
		$view = new View('frontend/forum.message.preview');
		
		$section_id = isset($_POST['message']['section_id']) ? $_POST['message']['section_id'] : NULL;
		$cat_id = isset($_POST['message']['cat_id']) ? $_POST['message']['cat_id'] : NULL;
		$topic_id = isset($_POST['message']['topic_id']) ? $_POST['message']['topic_id'] : NULL;
		
		if ( ! Valid::digit($section_id) OR ! Valid::digit($cat_id) OR ! Valid::digit($topic_id))
			throw new HTTP_Exception_404;
		
		$topic = ORM::factory('Forum_Topic')->where('id', '=', $topic_id)->find();
		$view->topic = $topic;
		
		if ( ! isset($topic->id) OR $topic->cat_id != $cat_id OR $topic->section_id != $section_id)
			throw new HTTP_Exception_404;
		
		$subscribed = ORM::factory('Forum_Subscribe')->where('topic_id', '=', $topic->id)->where('user_id', '=', Model_Reg::get('user')->id)->find();
		$view->subscribed = $subscribed;
		
		$this->template->content = $view;
	}
	
	public function action_previewtopic()
	{
		$view = new View('frontend/forum.topic.preview');
		
		$section_id = isset($_POST['topic']['section_id']) ? $_POST['topic']['section_id'] : NULL;
		$cat_id = isset($_POST['topic']['cat_id']) ? $_POST['topic']['cat_id'] : NULL;
		
		if ( ! Valid::digit($section_id) OR ! Valid::digit($cat_id))
			throw new HTTP_Exception_404;
		
		$cat = ORM::factory('Forum_Cat')->where('id', '=', $cat_id)->find();
		$view->cat = $cat;
		
		if ( ! isset($cat->id) OR $cat->section_id != $section_id)
			throw new HTTP_Exception_404;
		
		$this->template->content = $view;
	}
	
	public function action_edit()
	{
		$view = new View('frontend/forum.message.edit');
		
		$id = Request::current()->param('id');
		
		$message = ORM::factory('Forum_Message')->where('id', '=', $id)->find();
		$view->message = $message;
		
		if ( ! isset($message->id))
			throw new HTTP_Exception_404;
		
		if (Model_Reg::get('user')->id != $message->user_id)
			throw new HTTP_Exception_404;
		
		if ($message->topic->open == 0)
			throw new HTTP_Exception_404;
		
		$subscribed = ORM::factory('Forum_Subscribe')->where('topic_id', '=', $message->topic_id)->where('user_id', '=', $message->user_id)->find();
		$view->subscribed = $subscribed;
		
		$this->template->content = $view;
	}
	
	public function action_ajax_add_topic()
	{
		parent::is_ajax();
		
		$topic['name'] = isset($_POST['topic']['name']) ? trim(strip_tags($_POST['topic']['name'])) : NULL;
		$topic['user_id'] = Model_Reg::get('user')->id;
		$topic['section_id'] = isset($_POST['topic']['section_id']) ? trim(strip_tags($_POST['topic']['section_id'])) : NULL;
		$topic['cat_id'] = isset($_POST['topic']['cat_id']) ? trim(strip_tags($_POST['topic']['cat_id'])) : NULL;
		$topic['date'] = time();
		$topic['open'] = 1;
		$topic['deleted'] = 0;
		
		$message['text'] = isset($_POST['message']['text']) ? trim(strip_tags($_POST['message']['text'])) : NULL;
		$message['user_id'] = Model_Reg::get('user')->id;
		$message['section_id'] = isset($_POST['topic']['section_id']) ? trim(strip_tags($_POST['topic']['section_id'])) : NULL;
		$message['cat_id'] = isset($_POST['topic']['cat_id']) ? trim(strip_tags($_POST['topic']['cat_id'])) : NULL;
		$message['date'] = time();
		$message['deleted'] = 0;
		$message['ip'] = $_SERVER['REMOTE_ADDR'];
		
		if (empty($topic['name']))
		{
			$this->template->content = json_encode(array('status' => 'error', 'field' => 'topic_name', 'message' => 'Необходимо придумать название темы.'));
			return;
		}
		elseif ( ! Valid::digit($topic['user_id']) AND $topic['user_id'] < 1)
		{
			$this->template->content = json_encode(array('status' => 'error', 'field' => 'user_id', 'message' => 'Необходимо авторизоваться, чтобы добавить сообщение.'));
			return;
		}
		elseif (empty($topic['section_id']) OR ! Valid::digit($topic['section_id']))
		{
			$this->template->content = json_encode(array('status' => 'error', 'field' => 'section_id', 'message' => 'Параметр section_id неверный.'));
			return;
		}
		elseif (empty($topic['cat_id']) OR ! Valid::digit($topic['cat_id']))
		{
			$this->template->content = json_encode(array('status' => 'error', 'field' => 'cat_id', 'message' => 'Параметр cat_id неверный.'));
			return;
		}
		elseif (empty($message['text']))
		{
			$this->template->content = json_encode(array('status' => 'error', 'field' => 'message_text', 'message' => 'Введите текст.'));
			return;
		}
		
		$newtopic = ORM::factory('Forum_Topic')->values($topic);
		$newtopic->save();
		
		$newmessage = ORM::factory('Forum_Message')->values($message);
		$newmessage->topic_id = $newtopic->id;
		$newmessage->save();
		
		$newmessage->user->forum_total_messages = $newmessage->user->forum_messages->count_all();
		$newmessage->user->save();
		
		Model_Email_Forum::send_topic_to_admin($newtopic);
		
		// update subscribers database
		if (isset($_POST['message']['subscribe']) AND $_POST['message']['subscribe'] == 1)
		{
			$rel = ORM::factory('Forum_Subscribe')->where('user_id', '=', $newmessage->user_id)->where('topic_id', '=', $newmessage->topic_id)->find();
			$rel->user_id = $newmessage->user_id;
			$rel->topic_id = $newmessage->topic_id;
			$rel->save();
		}
		else
		{
			$rel = ORM::factory('Forum_Subscribe')->where('user_id', '=', $newmessage->user_id)->where('topic_id', '=', $newmessage->topic_id)->find();
			$rel->delete();
		}
		
		foreach (ORM::factory('User')->find_all() as $user)
		{
			$unreaded = ORM::factory('Forum_Topic_Unreaded');
			$unreaded->user_id = $user->id;
			$unreaded->cat_id = $newmessage->cat_id;
			$unreaded->topic_id = $newmessage->topic_id;
			$unreaded->save();
		}
		
		$this->template->content = json_encode(array('status' => 'success', 'topic_id' => $newtopic->id, 'message_id' => $newmessage->id));
		return;
	}
	
	public function action_ajax_add_message()
	{
		parent::is_ajax();
		
		$message['text'] = isset($_POST['message']['text']) ? trim(strip_tags($_POST['message']['text'])) : NULL;
		$message['user_id'] = Model_Reg::get('user')->id;
		$message['section_id'] = isset($_POST['message']['section_id']) ? trim(strip_tags($_POST['message']['section_id'])) : NULL;
		$message['cat_id'] = isset($_POST['message']['cat_id']) ? trim(strip_tags($_POST['message']['cat_id'])) : NULL;
		$message['topic_id'] = isset($_POST['message']['topic_id']) ? trim(strip_tags($_POST['message']['topic_id'])) : NULL;
		$message['date'] = time();
		$message['deleted'] = 0;
		$message['ip'] = $_SERVER['REMOTE_ADDR'];
		
		if ( ! Valid::digit($message['user_id']) AND $message['user_id'] < 1)
		{
			$this->template->content = json_encode(array('status' => 'error', 'field' => 'user_id', 'message' => 'Необходимо авторизоваться, чтобы добавить сообщение.'));
			return;
		}
		elseif (empty($message['section_id']) OR ! Valid::digit($message['section_id']))
		{
			$this->template->content = json_encode(array('status' => 'error', 'field' => 'section_id', 'message' => 'Параметр section_id неверный.'));
			return;
		}
		elseif (empty($message['cat_id']) OR ! Valid::digit($message['cat_id']))
		{
			$this->template->content = json_encode(array('status' => 'error', 'field' => 'cat_id', 'message' => 'Параметр cat_id неверный.'));
			return;
		}
		elseif (empty($message['topic_id']) OR ! Valid::digit($message['topic_id']))
		{
			$this->template->content = json_encode(array('status' => 'error', 'field' => 'topic_id', 'message' => 'Параметр topic_id неверный.'));
			return;
		}
		elseif (empty($message['text']))
		{
			$this->template->content = json_encode(array('status' => 'error', 'field' => 'message_text', 'message' => 'Введите текст.'));
			return;
		}
		
		$newmessage = ORM::factory('Forum_Message');
		$newmessage->values($message);
		
		if ($newmessage->topic->open == 0)
		{
			$this->template->content = json_encode(array('status' => 'error', 'field' => 'topic_id', 'message' => 'Тема закрыта, вы не можете добавить сообщение.'));
			return;
		}
		
		$newmessage->save();
		
		$newmessage->user->forum_total_messages = $newmessage->user->forum_messages->count_all();
		$newmessage->user->save();
		
		// send email to admins
		Model_Email_Forum::send_message_to_admin($newmessage);
		
		// update subscribers database
		if (isset($_POST['message']['subscribe']) AND $_POST['message']['subscribe'] == 1)
		{
			$rel = ORM::factory('Forum_Subscribe')->where('user_id', '=', $newmessage->user_id)->where('topic_id', '=', $newmessage->topic_id)->find();
			$rel->user_id = $newmessage->user_id;
			$rel->topic_id = $newmessage->topic_id;
			$rel->save();
		}
		else
		{
			$rel = ORM::factory('Forum_Subscribe')->where('user_id', '=', $newmessage->user_id)->where('topic_id', '=', $newmessage->topic_id)->find();
			$rel->delete();
		}
		
		// send emails to subscribers
		$subscribers = ORM::factory('Forum_Subscribe')->where('user_id', '!=', $newmessage->user_id)->where('topic_id', '=', $newmessage->topic_id)->find_all();
		foreach ($subscribers as $subscriber)
		{
			if (Valid::email($subscriber->user->email))
			{
				Model_Email_Forum::send_message_to_subscriber($newmessage, $subscriber->user);
			}
		}
		
		foreach (ORM::factory('User')->find_all() as $user)
		{
			$unreaded = ORM::factory('Forum_Topic_Unreaded');
			$unreaded->user_id = $user->id;
			$unreaded->cat_id = $newmessage->cat_id;
			$unreaded->topic_id = $newmessage->topic_id;
			$unreaded->save();
		}
		
		$this->template->content = json_encode(array('status' => 'success', 'topic_id' => $newmessage->topic_id, 'message_id' => $newmessage->id));
		return;
	}
	
	public function action_ajax_save_message()
	{
		parent::is_ajax();
		
		$id = Request::current()->param('id');
		
		// create new message
		if ($id === NULL)
		{
			$message['text'] = isset($_POST['message']['text']) ? trim(strip_tags($_POST['message']['text'])) : NULL;
			$message['user_id'] = Model_Reg::get('user')->id;
			$message['section_id'] = isset($_POST['message']['section_id']) ? trim(strip_tags($_POST['message']['section_id'])) : NULL;
			$message['cat_id'] = isset($_POST['message']['cat_id']) ? trim(strip_tags($_POST['message']['cat_id'])) : NULL;
			$message['topic_id'] = isset($_POST['message']['topic_id']) ? trim(strip_tags($_POST['message']['topic_id'])) : NULL;
			$message['date'] = time();
			$message['deleted'] = 0;
			$message['ip'] = $_SERVER['REMOTE_ADDR'];
			
			if ( ! Valid::digit($message['user_id']) AND $message['user_id'] < 1)
			{
				$this->template->content = json_encode(array('status' => 'error', 'field' => 'user_id', 'message' => 'Необходимо авторизоваться, чтобы добавить сообщение.'));
				return;
			}
			elseif (empty($message['section_id']) OR ! Valid::digit($message['section_id']))
			{
				$this->template->content = json_encode(array('status' => 'error', 'field' => 'section_id', 'message' => 'Параметр section_id неверный.'));
				return;
			}
			elseif (empty($message['cat_id']) OR ! Valid::digit($message['cat_id']))
			{
				$this->template->content = json_encode(array('status' => 'error', 'field' => 'cat_id', 'message' => 'Параметр cat_id неверный.'));
				return;
			}
			elseif (empty($message['topic_id']) OR ! Valid::digit($message['topic_id']))
			{
				$this->template->content = json_encode(array('status' => 'error', 'field' => 'topic_id', 'message' => 'Параметр topic_id неверный.'));
				return;
			}
			elseif (empty($message['text']))
			{
				$this->template->content = json_encode(array('status' => 'error', 'field' => 'message_text', 'message' => 'Введите текст.'));
				return;
			}
			
			$newmessage = ORM::factory('Forum_Message');
			$newmessage->values($message);
			
			if ($newmessage->topic->open == 0)
			{
				$this->template->content = json_encode(array('status' => 'error', 'field' => 'topic_id', 'message' => 'Тема закрыта, вы не можете добавить сообщение.'));
				return;
			}
			
			$newmessage->save();
			
			$newmessage->user->forum_total_messages = intval($newmessage->user->forum_messages->count_all());
			$newmessage->user->save();
			
				// send email to admins
			Model_Email_Forum::send_message_to_admin($newmessage);

			// update subscribers database
			if (isset($_POST['message']['subscribe']) AND $_POST['message']['subscribe'] == 1)
			{
				$rel = ORM::factory('Forum_Subscribe')->where('user_id', '=', $newmessage->user_id)->where('topic_id', '=', $newmessage->topic_id)->find();
				$rel->user_id = $newmessage->user_id;
				$rel->topic_id = $newmessage->topic_id;
				$rel->save();
			}
			else
			{
				$rel = ORM::factory('Forum_Subscribe')->where('user_id', '=', $newmessage->user_id)->where('topic_id', '=', $newmessage->topic_id)->find();
				$rel->delete();
			}

			// send emails to subscribers
			$subscribers = ORM::factory('Forum_Subscribe')->where('user_id', '!=', $newmessage->user_id)->where('topic_id', '=', $newmessage->topic_id)->find_all();
			foreach ($subscribers as $subscriber)
			{
				if (Valid::email($subscriber->user->email))
				{
					Model_Email_Forum::send_message_to_subscriber($newmessage, $subscriber->user);
				}
			}
			
			foreach (ORM::factory('User')->find_all() as $user)
			{
				$unreaded = ORM::factory('Forum_Topic_Unreaded');
				$unreaded->user_id = $user->id;
				$unreaded->cat_id = $newmessage->cat_id;
				$unreaded->topic_id = $newmessage->topic_id;
				$unreaded->save();
			}
			
			$this->template->content = json_encode(array('status' => 'success', 'topic_id' => $newmessage->topic_id, 'message_id' => $newmessage->id));
			return;
		}
		
		// update message
		else
		{
			$msg = ORM::factory('Forum_Message')->where('id', '=', $id)->find();
		
			if ( ! isset($msg->id))
				throw new HTTP_Exception_404;

			if (Model_Reg::get('user')->id != $msg->user_id)
				throw new HTTP_Exception_404;
			
			if ($msg->topic->open == 0)
			{
				$this->template->content = json_encode(array('status' => 'error', 'field' => 'topic_id', 'message' => 'Тема закрыта, вы не можете добавить сообщение.'));
				return;
			}

			$message['text'] = isset($_POST['message']['text']) ? trim(strip_tags($_POST['message']['text'])) : NULL;

			if (empty($message['text']))
			{
				$this->template->content = json_encode(array('status' => 'error', 'field' => 'message_text', 'message' => 'Введите текст.'));
				return;
			}

			$msg->values($message);
			$msg->save();
			
			// update subscribers database
			if (isset($_POST['message']['subscribe']) AND $_POST['message']['subscribe'] == 1)
			{
				$rel = ORM::factory('Forum_Subscribe')->where('user_id', '=', $msg->user_id)->where('topic_id', '=', $msg->topic_id)->find();
				$rel->user_id = $msg->user_id;
				$rel->topic_id = $msg->topic_id;
				$rel->save();
			}
			else
			{
				$rel = ORM::factory('Forum_Subscribe')->where('user_id', '=', $msg->user_id)->where('topic_id', '=', $msg->topic_id)->find();
				if (isset($rel->id)) $rel->delete();
			}

			$this->template->content = json_encode(array('status' => 'success', 'topic_id' => $msg->topic_id, 'message_id' => $msg->id));
			return;
		}
	}
	
}